package com.mxc.split.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.mxc.split.entity.Product;
import com.mxc.split.service.ProductService;
import com.mxc.split.util.MyUtil;
import com.mxc.split.util.SnowFlake;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@SuppressWarnings(value = { "unchecked", "rawtypes" })
public class ProductController {

	@Autowired
	private ProductService productService;

	@Autowired
	private RedisTemplate redisTemplate;

	@RequestMapping("/generateOrderId")
	public Object generateOrderId(String userName) {
		Long result = redisTemplate.opsForValue().increment(userName);
		String orderId = MyUtil.renderOrderId(result);
		System.out.println(userName + ":" + orderId);
		return orderId;
	}

	@RequestMapping("/test")
	public Object testSnowFlake() {
		SnowFlake snowFlake = new SnowFlake(10, 30);
		Map<Integer, Long> map = new HashMap<Integer, Long>();
		for (int i = 0; i < 10; i++) {
			map.put(i, snowFlake.nextId(false));
		}
		return map;
	}

	@RequestMapping("/save")
	public Object save(Date date) {
		SnowFlake snowFlake = new SnowFlake(10, 30);
		long snowFlakeId = snowFlake.nextId(false);
		Product product = new Product();
		product.setId(snowFlakeId);
		product.setName("测试雪花算法生成唯一id");
		product.setCreateTime(date);
		productService.saveProduct(product);
		return "success";
	}

	@RequestMapping("/save1")
	public Object save1() {
		SnowFlake snowFlake = new SnowFlake(10, 30);
		for (int i = 0; i < 10; i++) {
			long snowFlakeId = snowFlake.nextId(false);
			System.out.println(snowFlakeId);
			Product product = new Product();
			product.setName("测试雪花算法生成唯一id");
			product.setId(snowFlakeId);
			product.setCreateTime(new Date());
			productService.saveProduct(product);
		}
		return 1;
	}

	public static void main(String[] args) throws Exception {
		SnowFlake snowFlake = new SnowFlake(2, 3);
		for (int i = 0; i < 10; i++) {
			long snowFlakeId = snowFlake.nextId(false);
			System.out.println(snowFlakeId);
			Thread.sleep(1);
		}
	}

	@RequestMapping("/getId")
	public Object getById(Long id) {
		return productService.selectById(id);
	}

	@RequestMapping("/all")
	public Object getAll() {
		return productService.getAllProducts();
	}

	@RequestMapping("/getByName")
	public Object getListByName(String name) {
		return productService.list(name);
	}
}
